<template>
  <!-- 新增插入地图 -->
  <div id="map">
    <!-- <p id="currentPoint">
      <i class="el-icon-location"></i>
      {{ currentPoint.lat?currentPoint.lat.toFixed(4):"-" }}, {{ currentPoint.lng?currentPoint.lng.toFixed(4):"-" }}
    </p> -->
    <dl class="tipItem">
      <dt>图例</dt>
      <dd style="border-bottom:1px solid #afa9a9;">
        <img src="~@/assets/images/marker.png" />
        <span>机场</span>
      </dd>
      <dd>
        <img src="~@/assets/images/airpoint.png" />
        <span>航路点</span>
      </dd>
    </dl>
    <dl class="chooseItem">
      <dt>筛选</dt>
      <dd :class="checkItem.includes('airspace')?'activeItem':''" @click="listenCheck('airspace')">
        <span>空域</span>
        <i class="el-icon-check" v-show="checkItem.includes('airspace')"></i>
      </dd>
      <dd :class="checkItem.includes('airport')?'activeItem':''" @click="listenCheck('airport')">
        <span>机场</span>
        <i class="el-icon-check" v-show="checkItem.includes('airport')"></i>
      </dd>
      <dd :class="checkItem.includes('airpoint')?'activeItem':''" @click="listenCheck('airpoint')">
        <span>航路点</span>
        <i class="el-icon-check" v-show="checkItem.includes('airpoint')"></i>
      </dd>
      <dd :class="checkItem.includes('airline')?'activeItem':''" @click="listenCheck('airline')">
        <span>航线</span>
        <i class="el-icon-check" v-show="checkItem.includes('airline')"></i>
      </dd>
    </dl>
  </div>
</template>

<script>
  import { Loading } from 'element-ui';
  var loadingInstance;
  var airspaceLayer = null; // 空域图层
  var airportLayer = null;  // 机场图层
  var pointLayer = null;  // 航路点层
  var lineLayer = null, linePointLayer = null; // 航线图层|航线点位图层
  // var sector;
  // var myIcon = L.icon({
  //   iconUrl: require('@/assets/images/station.png'),
  //   iconSize: [18, 22],
  //   iconAnchor: [22, 94],
  //   popupAnchor: [-3, -76],
  //   shadowUrl: 'my-icon-shadow.png',
  //   shadowSize: [68, 95],
  //   shadowAnchor: [22, 94]
  // });
  export default {
    name: 'MapInsert',
    data() {
      return {
        map:null,
        airspaceList:[],  // 空域列表
        airspaceLayerGroup:[],  // 空域图层
        
        airportList:[],   // 机场列表
        airportLayerGroup:[],  // 机场图层

        airpointList:[],   // 航路点列表
        airpointLayerGroup:[],  // 航路点图层

        airlineList:[],   // 航线列表
        airlineLayerGroup:[],  // 航线图层
        checkItem:["airspace","airport","airpoint","airline"], // 选中的要显示的信息
        currentPoint:{
          lng:null,
          lat:null
        },
      }
    },
    mounted(){
      this.$nextTick(()=>{
        // var normalm =  L.esri.tiledMapLayer({
        //   url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer'
        // });
        // var satelliteImgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map');
        // var satelliteImga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion');

        var normalm = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
          maxZoom: 18,
          minZoom: 4
        });
        var satelliteImgm = L.tileLayer.chinaProvider('GaoDe.Satellite.Map');
        var satelliteImga = L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion');
        var satellite = L.layerGroup([satelliteImgm, satelliteImga]);
        var normal = L.layerGroup([normalm]);
        let layerName = {
          "卫星地图":satellite,
          "普通地图":normal
        }
        this.map = L.map("map",{
          center:[40.2646, 116.3991],
          zoom:8,
          layers:[satellite, normal],
          preferCanvas:true,
          zoomControl:false,
          attributionControl:false,
          inertia:false,
          trackResize:true
        });
        L.control.layers(layerName).addTo(this.map);
        // 比例尺
        L.control.scale({imperial:false}).addTo(this.map);
        // 缩放
        L.control.zoom().addTo(this.map);
        // this.map.setView([data.latGCJ02, data.lonGCJ02], 8)
        
        // 绘制扇形
        // this.drawSector([31.59586, 120.2995], 0.02, -60, 45, 800);

        // 监听地图点击事件
        this.map.on('click', (e)=>{
          // console.log(e)
        })

        // 监听地图鼠标移动事件
        this.map.on('mousemove', (e)=>{
          // this.currentPoint.lng = e.latlng.lng;
          // this.currentPoint.lat = e.latlng.lat;
        })

        // 监听地图移动事件
        // this.map.on('move', (e)=>{})

        // 监听地图缩放事件
        this.map.on('zoom', (e)=>{
          // if(e.target._zoom <= 7 && this.isShow){
          //   this.isShow = false;
          //   document.getElementsByClassName("iconLabel").forEach(item=>{
          //     item.style.display = "none";
          //   })
          // }
          // if(e.target._zoom > 7 && !this.isShow){
          //   this.isShow = true;
          //   document.getElementsByClassName("iconLabel").forEach(item=>{
          //     item.style.display = "block";
          //   })
          // }
        })

        window.onresize = ()=>{
          this.map.invalidateSize(true);
          // this.map.fitBounds([
          //   [31.59102002701019, 120.30037886225469],
          //   [31.589045999457486, 120.30016433385363],
          //   [31.589064277682226, 120.30222380650356],
          //   [31.59586, 120.2995]
          // ]);
        }
      })
    },
    methods:{
      // 绘制空域
      drawAirspace(airspaceList, color){
        console.log(airspaceList, color);
        this.airlineList = airspaceList;
        if(airspaceLayer) this.map.removeLayer(airspaceLayer);
        this.airspaceLayerGroup = [];
        if(airspaceList.length){
          let arr = [];
          airspaceList.map((item, i)=>{
            if(item.spacePoints && item.spacePoints.length){
              switch (item.spaceShape) {
                case 1:
                  // 多边形
                  item.spacePoints.map((vo, index)=>{
                    arr.push([vo.pLat, vo.pLng]);
                    if(index == item.spacePoints.length-1){
                      this.airspaceLayerGroup.push(L.polygon(arr, {color:color}).bindPopup(item.spaceName));
                    }
                  })
                  break;
                case 2:
                  // 圆形
                  let radius = Number(item.spacePoints[0].pRadius) * 1000;
                  this.airspaceLayerGroup.push(L.circle([item.spacePoints[0].pLat, item.spacePoints[0].pLng], {
                    color: color,
                    // fillColor:'transparent',
                    radius: radius
                  }).bindPopup(item.spaceName));
                  break;
                case 3:
                  // 扇形
                  var points = this.getPoints([item.spacePoints[0].pLat, item.spacePoints[0].pLng], item.spacePoints[0].pRadius, item.spacePoints[0].pAngleStart, item.spacePoints[0].pAngleEnd, 800);
                  points[points.length] = points[0];
                  this.airspaceLayerGroup.push(L.polygon(points, {color:color}).bindPopup(item.spaceName))
                  break;
              }
            }
            if(i == airspaceList.length-1){
              airspaceLayer = L.layerGroup(this.airspaceLayerGroup.reverse());
              airspaceLayer.addTo(this.map);
              this.map.setView([item.spacePoints[0].pLat, item.spacePoints[0].pLng], 8);
            }
          })
        }
      },

      // 绘制机场
      drawAirport(airportList){
        console.log(airportList);
        this.airportList = airportList;
        if(airportLayer) this.map.removeLayer(airportLayer);
        this.airportLayerGroup = [];
        if(!airportList.length) return false;
        airportList.map((info, i)=>{
          if(info.portLongValue && info.portLatValue){
            var pointIcon = L.divIcon({
              html:'<img class="my-div-image" style="width:14px;height:14px;" src="'+require("@/assets/images/marker.png")
              +'" /><span class="iconLabel" style="padding:6px 10px;margin:-5px 0 0 -8px;color:#595656;background-color:#FFF;border-radius:5px;border:1px solid #595656;white-space:nowrap;">'
              +info.portName+'</span>',
              className: 'my-div-icon'
            });
            // let pointIcon = L.icon({
            //   iconUrl: require('@/assets/images/marker.png'),
            //   iconSize: [10, 10]
            // });
            let marker = L.marker([info.portLatValue, info.portLongValue], {icon: pointIcon})
            .bindPopup("<div style='padding:5px;'><b>"+info.portName+"</b><br/>经纬度:"+info.portLatitude+","+info.portLongitude+"</div>");
            this.airportLayerGroup.push(marker);
          }
          if(i == airportList.length-1){
            airportLayer = L.layerGroup(this.airportLayerGroup.reverse());
            airportLayer.addTo(this.map);
            this.map.setView([info.portLatValue, info.portLongValue], 8);
          }
        })
      },

      // 绘制航路点
      drawAirpoint(airpointList){
        console.log(airpointList);
        this.airpointList = airpointList;
        if(pointLayer) this.map.removeLayer(pointLayer);
        this.airpointLayerGroup = [];
        if(!airpointList.length) return false;
        airpointList.map((info, i)=>{
          if(info.pointLngValue && info.pointLatValue){
            let pointIcon = L.icon({
              iconUrl: require('@/assets/images/airpoint.png'),
              iconSize: [18, 22]
            });
            let marker = L.marker([info.pointLatValue, info.pointLngValue], {icon: pointIcon})
            .bindPopup("<div style='padding:5px;'><b>"+info.pointName+"</b><br/>经纬度:"+info.pointLatitude+","+info.pointLongitude+"</div>");
            this.airpointLayerGroup.push(marker);
          }
          if(i == airpointList.length-1){
            pointLayer = L.layerGroup(this.airpointLayerGroup.reverse());
            pointLayer.addTo(this.map);
            this.map.setView([info.pointLatValue, info.pointLngValue], 8);
          }
        })
      },

      // 绘制航线
      drawAirline(lineList, color){
        console.log(lineList, color);
        if(lineLayer) this.map.removeLayer(lineLayer);
        if(linePointLayer) this.map.removeLayer(linePointLayer);
        this.airlineLayerGroup = [];
        let pointIcon = L.icon({
          iconUrl: require('@/assets/images/marker.png'),
          iconSize: [8, 8]
        });
        if(lineList.length){
          lineList.map((info, i)=>{
            let linePointArr = [], lineArr = [], polyline = null;
            if(info.linePoints && info.linePoints.length){
              info.linePoints.map((vo, index)=>{
                if(vo.pLat && vo.pLng){
                  lineArr.push([vo.pLat, vo.pLng]);
                  let marker = L.marker([vo.pLat, vo.pLng], {icon: pointIcon})
                  .bindPopup("<div style='padding:5px;'><b>"+vo.pName+"</b><br/>经纬度:"+vo.pLatDis+","+vo.pLngDis+"</div>");
                  linePointArr.push(marker)
                }
                if(index == info.linePoints.length-1){
                  polyline = L.polyline(lineArr, {color:color}).bindPopup(item.pName);
                  this.airlineLayerGroup.push(polyline);
                }
              })
            }
            if(i == lineList.length-1){
              linePointLayer = L.layerGroup(linePointArr);
              linePointLayer.addTo(this.map);
              lineLayer = L.layerGroup(this.airlineLayerGroup.reverse());
              lineLayer.addTo(this.map);
              this.map.fitBounds(this.airlineLayerGroup[0].getBounds());
            }
          })
        }
      },

      // 地图信息是否显示监听
      listenCheck(val){
        if(this.checkItem.includes(val)){
          this.checkItem.forEach((item, index)=>{
            if(item == val){
              this.checkItem.splice(index, 1);
              return false;
            }
          })
        }else{
          this.checkItem.push(val);
        }

        switch (val) {
          case "airspace":
            if(!airspaceLayer) return false;
            if(this.checkItem.includes("airspace")){
              airspaceLayer.addTo(this.map);
            }else{
              this.map.removeLayer(airspaceLayer);
            }
            break;
          case "airport":
            if(!airportLayer) return false;
            if(this.checkItem.includes("airport")){
              airportLayer.addTo(this.map);
            }else{
              this.map.removeLayer(airportLayer);
            }
            break;
          case "airpoint":
            if(!pointLayer) return false;
            if(this.checkItem.includes("airpoint")){
              pointLayer.addTo(this.map);
            }else{
              this.map.removeLayer(pointLayer);
            }
            break;
          case "airline":
            if(!lineLayer) return false;
            if(this.checkItem.includes("airline")){
              lineLayer.addTo(this.map);
              linePointLayer.addTo(this.map);
            }else{
              this.map.removeLayer(lineLayer);
              this.map.removeLayer(linePointLayer);
            }
            break;
        }
      },

      // 清除图层
      clearAllLayer(){
        if(airspaceLayer) this.map.removeLayer(airspaceLayer);
        if(airportLayer) this.map.removeLayer(airportLayer);
        if(pointLayer) this.map.removeLayer(pointLayer);
        if(lineLayer) this.map.removeLayer(lineLayer);
        if(linePointLayer) this.map.removeLayer(linePointLayer);
      },

      // 清空地图信息
      clearMapInfo(){
        this.clearAllLayer();
        airspaceLayer = null;
        airportLayer = null;
        pointLayer = null;
        lineLayer = null;
        linePointLayer = null;
        this.airspaceLayerGroup = [], this.airspaceList = [];
        this.airportList = [], this.airportLayerGroup = [];
        this.airpointList = [], this.airpointLayerGroup = [];
        this.airlineList = [], this.airlineLayerGroup = [];
      },

      /* 
       * 绘制扇形
       * @params center 扇形中心点 Array [31.59586, 120.2995]
       * @params radius 扇形半径 Number
       * @params startArc 起始角度 Number -180-180 逆时针取值
       * @params stopArc 终止角度 Number -180-180 逆时针取值
       * @params pointNum 圆弧上点的个数 Number
      */
      getPoints(center, radius, startArc, stopArc, pointNum){
        var sin;
        var cos;
        var x;
        var y;
        var angle;
        var points = [];
        points.push(center);
        for (var i = 0; i <= pointNum; i++) {
            angle = startArc + (stopArc - startArc) * i / pointNum;
            sin = Math.sin(angle * Math.PI / 180);
            cos = Math.cos(angle * Math.PI / 180);
            y = center[0] + radius * cos;
            x = center[1] + radius * sin;
            points[i] = [y, x];
        }
        var point = points;
        point.push(center);
        return point;
      },
      drawSector(center, radius, startArc, stopArc, pointNum){
        var points = this.getPoints(center, radius, startArc, stopArc, pointNum);
        points[points.length] = points[0];
        sector = L.polygon(points, {color:"purple"}).addTo(this.map).bindPopup("(*^▽^*)").openPopup();
      },
    },
    beforeDestroy(){
      if(this.map){
        this.map = null;
        this.$parent.$refs.mapPart.map = null;
      }
    },
  }
</script>
<style scoped>
  #mainPart{
    width:100%;
    height:100vh;
    padding:0;
    overflow: hidden;
    position:relative;
  }
  /* div >>> .leaflet-top.leaflet-left{
    left:10px;
    top:90px!important;
  } */
  /* 地图 */
  #map{
    width:100%;
    height:100%;
    padding:0;
    margin:0;
    position: relative;
  }
  .airportIcon{
    width:5px;
    height:5px;
    display:block;
    background-color:red;
    border-radius:100%;
  }
  /* 点位显示 */
  #currentPoint{
    height:30px;
    line-height:20px;
    font-size:14px;
    background-color:#F2F2F2;
    padding:5px 8px;
    margin:0;
    position:absolute;
    bottom:10px;
    right:10px;
    z-index:9999;
  }
  /* 图例 */
  dl.tipItem{
    width:90px;
    height:100px;
    background-color:#F2F2F2;
    border-radius:5px;
    position:absolute;
    bottom:10px;
    right:10px;
    z-index:999;
  }
  dl.tipItem dt{
    width:100%;
    height:28px;
    line-height:28px;
    font-size:14px;
    text-align:center;
    color:#FFF;
    background-color:#1f2d3d;
    border-bottom:1px solid #1f2d3d;
    border-radius:5px 5px 0 0;
  }
  dl.tipItem dd{
    width:100%;
    height:36px;
    line-height:36px;
    text-align: left;
    display:inline-block;
    padding:0 10px;
    margin:0;
  }
  dl.tipItem dd img{
    width:20px;
    vertical-align:middle;
    margin-right:14px;
  }
  /* 筛选 */
  .chooseItem{
    width:90px;
    font-size:14px;
    color:#4c4949;
    text-align:center;
    background-color:#FFF;
    border-radius:5px;
    position:absolute;
    top:60px;
    right:10px;
    z-index:999;
  }
  .chooseItem dt, .chooseItem dd{
    width:100%;
    margin:0;
    cursor:pointer;
    display:flex;
    display:-webkit-flex;
    align-items:center;
    letter-spacing: 1px;
  }
  .chooseItem dt{
    height:30px;
    line-height:30px;
    color:#FFF;
    background-color:#1f2d3d;
    border-bottom:1px solid #CCC;
    justify-content:center;
    border-radius:5px 5px 0 0;
  }
  .chooseItem dd{
    height:40px;
    line-height:40px;
    padding:0 8px;
    justify-content:flex-start;
  }
  .chooseItem dd:last-child{
    border-radius:0 0 5px 5px;
  }
  .chooseItem img{
    width:22px;
    height:22px;
    vertical-align:middle;
  }
  .chooseItem .activeItem .el-icon-check{
    font-size:12px;
    font-weight:bolder;
    color:#2C92DC;
  }
  .chooseItem .activeItem{
    color:#2C92DC;
    justify-content:space-between;
  }

  /* 表格 */
  .el-table{
    width:calc(100% - 16px);
    font-size:13px;
    border:1px solid #243F63;
  }
  .el-table td, .el-table th, .el-table--small td, .el-table--small th{
    padding:4px 0!important;
    height:30px;
    padding:5px 0;
  }
  .el-table th, .el-table thead.is-group th, .el-table--small th{
    height: 30px!important;
    background-color:#063761!important;
    font-size:13px;
    color:#FFF;
    border:1px solid #063761;
  }
  .el-table thead.is-group th{
    border-bottom:1px solid #063761;
  }
  .el-table .cell{
    height:100%;
    line-height:29px;
    text-align:center;
    overflow: hidden;
    white-space: nowrap!important;
    text-overflow: ellipsis;
  }
  .el-table__body tr.current-row>td,
  .el-table--enable-row-hover .el-table__body tr:hover>td,
  .el-table__body tr.hover-row>td.el-table__cell,
  .el-table__body tr.el-table__row:hover td.el-table__cell{
    background-color: #156FA1!important;
    color: #FFF;
    cursor: pointer;
  }
  .el-table td .el-button{margin:0px!important;}
  .el-table td .el-button--text span{
    letter-spacing: 1px;
    border-bottom: 1px solid;
    padding-bottom:1px;
    margin: 0 3px;
  }
  .el-table--border:after, .el-table--group:after, .el-table:before{
    background-color:transparent!important;
  }
  .el-table, .el-table >>> th{
    color:#FFF;
    background-color:transparent;
    border:none!important;
    margin:0;
  }
  .el-table >>> th{
    border:none!important;
    background-color:#071629!important;
  }
  .el-table >>> th.el-table__cell, .el-table >>> td.el-table__cell{
    border:none!important;
  }
  .el-table >>> tbody tr:hover td{
    background-color:#0A1B31;
  }
  .el-table >>> tbody tr:nth-child(odd){
    background-color:#0A1B31;
  }
  .el-table >>> tbody tr:nth-child(even){
    background-color:#071629;
  }
  .el-table >>> .el-table__header-wrapper th,
  .el-table >>> .el-table__fixed-header-wrapper th{
    background-color:#000A2E;
    border:none!important;
    color:#e6dede;
  }
  .el-table >>> td.el-table__cell, .el-table >>> th.el-table__cell.is-leaf{
    border:none!important;
    background-color:transparent;
    line-height:29px;
  }
</style>